var tool = require("./tool"),
    fs = require("fs"),
    path = require("path"),
    upload2Cdn = require("./upload2Cdn"),
    deployInfo = require("../../deploy-conf.json"),
    namespaces = deployInfo.namespaces,
    version = deployInfo.version;

module.exports = function (next) {
    require("colors");
    require("shelljs/global");
    var prompt = require("prompt");

    if (fs.existsSync("./." + namespaces)) {
        exec("rm -rf ." + namespaces);
    }

    var filerReg = /\.js$|\.css$|\.html$|(\.png$|\.gif$|\.jpg$|\.jpeg$|\.webp$)|(\.mp4$|\.ogv$|\.webm$)/;
    var files = tool.getAllFiles("./", filerReg);
    files = filterFiles(files, false);

    console.log("\n1. input your git.oschina username and passwd to git clone prev version files：\n".green);
    exec("git clone " + deployInfo.gitpath + " ." + namespaces);

    var oldfiles = tool.getAllFiles("./." + namespaces, filerReg);
    oldfiles = filterFiles(oldfiles, true);

    console.log("\n2. your current modify files：".green);
    var tmp = [];
    for (var key in files) {
        if (key in oldfiles) {
            if (oldfiles[key] != files[key]) {
                tmp.push(key);
            }
        } else {
            tmp.push(key);
        }
    }

    for (var i = 0, len = tmp.length; i < len; i++) {
        console.log(tmp[i]);
    }
    console.log("\n");

    if (!tmp.length) {
        console.log("no files modify, we dont need to upload...=^=".red);
        process.exit(0);
    }

    prompt.start();
    prompt.get({
        properties: {
            back: {
                message: "ensure to deploy(y/n)",
                required: true
            }
        }
    }, function (err, result) {
        if (result.back == "y") {
            var ZipWriter = require("moxie-zip").ZipWriter;
            var zip = new ZipWriter();
            for (var i = 0, len = tmp.length; i < len; i++) {
                zip.addFile(tmp[i], tmp[i]);
            }

            var zipname = namespaces + "-" + version + "-" + (+new Date()) + ".zip";
            zip.saveAs(zipname, function () {
                upload2Cdn([{
                    filename: zipname,
                    path: "./" + zipname
                }], function () {
                    exec("rm -rf " + zipname);
                    console.log("\nupload zip complete, change the version json file, plz wait...".green);

                    var versionFilename = namespaces + "-version.json";
                    var url = deployInfo.domains[0] + "/" + versionFilename;
                    var request = require("request");
                    request.get(url, function (err, res, body) {
                        if (err) {
                            console.log(err.red);
                        } else {
                            /**
                             * version file:
                             * {
                             *     "version" : "0.0.1",
                             *     "file": "http://static.petera.cn/fiber-0.0.1-xxxx.zip"
                             * }
                             */
                            if (res.statusCode == 200 || res.statusCode == 404) {
                                body = res.statusCode == 404 ? {} : JSON.parse(body);
                                body.version = version;
                                body.file = deployInfo.domains[0] + "/" + zipname;
                            } else {
                                console.log(("response header status code is " + res.statusCode).red)
                                process.exit(0);
                            }

                            err = fs.writeFileSync(versionFilename, JSON.stringify(body));
                            if (err) {
                                console.log(("write version file faild, err:".err).red);
                                process.exit(0);
                            }

                            upload2Cdn([{
                                filename: versionFilename,
                                path: "./" + versionFilename
                            }], function () {
                                exec("rm -rf " + versionFilename);
                                console.log("\nall success, plz refresh your version file in cdn ^_^...\n".green);
                            }, true);
                        }
                    });
                });
            });

        } else {
            process.exit(0);
        }
    });
};

function filterFiles(files, changePrefix) {
    var md5File = require('md5-file');
    var map = {};
    files.filter(function (v) {
        return v.path && v.path.indexOf(".build") == -1
    }).forEach(function (v) {
        if (changePrefix) {
            var prefix = './.' + namespaces;
            var key = v.path.slice(v.path.indexOf(prefix) + prefix.length);
            map["./" + key] = md5File(v.path);
        } else {
            map[v.path] = md5File(v.path);
        }
    });
    return map;
}
